package com.xmutca.sso.server.realm;

import com.xmutca.core.common.Result;
import com.xmutca.sso.api.Account;
import com.xmutca.sso.api.server.AccountService;
import com.xmutca.sso.common.Principal;
import com.xmutca.sso.server.token.UsernamePasswordToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

/**
 * @author: 彭伟煌(pengweihuang@xmutca.com)
 * @create: 2016-08-08 14:11
 */
public class SystemRealm extends AuthorizingRealm {

    private AccountService accountService;

    /**
     * 授权，并不会走sso服务器的授权通道
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;

        Result<Account> account = accountService.getByUsername(token.getUsername());
        if(account.getResult() == null) {
            throw new UnknownAccountException();//没找到帐号
        }

        //赋予属性
        SecurityUtils.getSubject().getSession().setAttribute("xmlHttpRequest", token.isXmlHttpRequest());

        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                new Principal(account.getResult()),//用户信息，需要多少信息就为对象赋多少属性
                account.getResult().getPassword(),//用户被加密过的密码
                ByteSource.Util.bytes(account.getResult().getSalt()),//解密的钥匙(与加密钥匙一样)
                getName());
        return authenticationInfo;
    }

    public void setAccountService(AccountService accountService) {
        this.accountService = accountService;
    }
}